package com.xlserver.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xlserver.util.model.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@Api(value = "文件上传", tags = "文件上传")
public class FileUploadController {

    //绑定文件上传路径到uploadPath
    @Value("${web.upload-path}")
    private String uploadPath;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");


    @ApiOperation(value = "文件上传", notes = "userInfo及对象中的profilePhoto")
    public String upload(@RequestBody MultipartFile uploadFile,
                         HttpServletRequest request) throws IOException {
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        // 文件保存
        uploadFile.transferTo(new File(folder, newName));

        // 返回上传文件的访问路径
        String filePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort()  +"/"+ format + newName;
        return filePath;
    }
    @PostMapping("/upload")
    //    修改用户头像
    public static String saveImage(MultipartFile image) throws IOException {
        String originalFilename = image.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
        File uploadFile = new File("C:/images/" + fileUUID);
        System.out.println("uploadFile:"+uploadFile);
        // 上传文件到磁盘
        image.transferTo(uploadFile);
        // 数据库若不存在重复文件，则不删除刚才上传的文件
        String url = "http://localhost:8080/headImage/" + fileUUID;
        return url;
    }
}

